package chapter07

object Demo15_HighLevelFunction_Reduce {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4)
    //    （6）简化（规约） reduce
    println(list.reduce((a: Int, b: Int) => (a + b)))
    println(list.reduceLeft(_ + _))
    println(list.reduceRight(_ + _))

    println("============")

    val list2 = List(3, 4, 5, 8, 9)
    println(list2.reduce(_ - _))
    println(list2.reduceLeft(_ - _))
    println(list2.reduceRight(_ - _)) //3-(4-(5-(8-9)))   5
    println("=======================")

    //    （7）折叠   fold
    println(list.fold(10)(_ + _)) //10 + 1 + 2 + 3 + 4
    println(list.foldLeft(10)(_ - _))
    println(list.foldRight(10)(_ - _)) // 1 - (2 - (3 - (4 -10)))
  }
}
